package net.meblabs.bookapp.web.controller;

import java.util.Date;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

import net.meblabs.commons.progress.ComplexProgress;
import net.meblabs.commons.progress.Progress;
import net.meblabs.commons.progress.ProgressRegistry;
import net.meblabs.commons.progress.comm.InitProgressMessage;
import net.meblabs.commons.progress.comm.ProgressMessage;
import net.meblabs.commons.progress.comm.ProgressMessage.Type;
import net.meblabs.commons.progress.comm.StateProgressMessage;

import org.apache.commons.lang.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping(value = "/progress", method = RequestMethod.GET)
public class ProgressController {

	private static final int MAX = 13;
	private static final String INIT_MSG = "Monitor was initialized";
	private static final Logger log = LoggerFactory.getLogger(ProgressController.class);

	@RequestMapping("/{progressId}")
	public @ResponseBody
	ProgressMessage ask(@PathVariable("progressId") Long progressId) {
		Progress progress = ProgressRegistry.getProgress(progressId);
		if (progress == null) {

		}

		StateProgressMessage stateMessage;
		if (progress.getState().getDonePercent() == 100) {
			stateMessage = new StateProgressMessage(progress.getId(), Type.DONE);
		} else {
			stateMessage = new StateProgressMessage(progress.getId(), Type.MORE);
		}
		stateMessage.setState(progress.getState());
		if (progress instanceof ComplexProgress) {
			stateMessage.setSubState(((ComplexProgress) progress).getSubProgressState());
		}
		return stateMessage;
	}

	@RequestMapping("/init")
	public @ResponseBody
	InitProgressMessage init() {
		Progress progress = ProgressRegistry.createProgress();
		progress.initialize(MAX, INIT_MSG);
		initTimerTask(progress.getId(), MAX);
		return new InitProgressMessage(progress.getId(), "Import autorów");
	}

	private void initTimerTask(final Long progressId, final int max) {
		Timer timer = new Timer();
		timer.schedule(new TimerTask() {

			private Random r = new Random();
			private int sofar = 0;

			@Override
			public void run() {
				try {
					if (sofar >= max) {
						cancel();
						return;
					}
					int millis = r.nextInt(1000) + 500;
					Thread.sleep(millis);
					String message = "Waited for " + millis + " milliseconds";
					ProgressRegistry.getProgress(progressId).advance(message);
					log.info(message);
					sofar++;
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}, DateUtils.addSeconds(new Date(), 1), 1000);
	}
}
